/**
 * @author LYJ
 * Created by Administrator on 2018/3/1 0001.
 */
function FoodTypeTable($Table,type) {
    var This = this;
    this.div = $Table;
    this.userId = $Table.attr("data-userId");
    this.type = type
    this.tableBar = null;
    this.toolBar = null;
    this.errorBar = null;
    this.path = "../static/";

    this.foodtypeForm = null;
    this.foodtypeTransferForm = null;

    $(function () {
        This.div.html("");
        This.createTool.init();//表工具
        This.createTable.init();//创建数据表
    });


    this.createTool  = {
        init: function () {
            this.bar();
            this.element();
            this.event();
        },
        bar: function () {
            var toolbar =
                '<div class="error"></div>'+
                '<div class="myToolbar"><div class="fClear" style=" clear:both;"></div></div>'+
                '<div class="toolbar btn-group pull-right"  style="margin-right: 10px" ></div>';
            This.div.append(toolbar);
            This.errorBar = This.div.find(".error");
            This.errorBar.hintModal();
            This.toolBar = This.div.find(".toolbar");
            This.myToolBar = This.div.find(".myToolbar");
        },
        element: function () {
            addTool(
                '<button class="add btn btn-default FL" style="margin-right: 10px">' +
                '<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增' +
                '</button>'
            );
        },
        event: function () {
            getTool("add").bind("click",function () {
                This.foodtypeForm.$modal.hintModal().showDiv();
                This.foodtypeForm.setType("add");
            });
        }
    };

    this.createTable = {
        init: function () {
            var tableHtml = '<table style="min-width: 700px"></table>';
            This.div.append(tableHtml);
            This.tableBar = This.div.find("table");

            var table = This.tableBar;
            This.tableBar.bootstrapTable({
                method: 'post',                      //请求方式（*）
                url: "foodtype/get",         //请求后台的URL（*）
                toolbar: '.toolbar',
                queryParams: this.queryParams,//传递参数（*）
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
                contentType: "application/x-www-form-urlencoded",
                // height:$(document).height() - This.div.offset().top - 20,
                showColumns: true,                  //是否显示所有的列
                showRefresh: true,                  //是否显示刷新按钮
                clickToSelect: true,                //是否启用点击选中行
                uniqueId: "typeid",                     //每一行的唯一标识，一般为主键列
                columns: [
                    {
                        width: "5%",
                        align: "center",
                        formatter: function (value, row, index) {
                            var options = table.bootstrapTable('getOptions');
                            return options.pageSize * (options.pageNumber - 1) + index + 1;
                        }
                    },
                    {
                        field: 'picurl',
                        align: "center",
                        valign: "middle",
                        formatter: function (value, row, index) {
                            return '<img src="'+This.path + (value ? value : "img/selectImage/emptyImg.png")+'" width="30px" height="30px">';
                        }
                    },
                    {
                        title:'名称',
                        field: 'typename',
                        align: "center",
                        valign: "middle"
                    },
                    {
                        title:'数量',
                        field: 'size',
                        align: "center",
                        valign: "middle"
                    },
                    {
                        title:'创建时间',
                        field: 'createTime',
                        align: "center",
                        valign: "middle",
                        formatter:function (value, row, index) {
                            if(value != null){
                                return '<p title="'+value+'">'+value.split(" ")[0]+'</p>';
                            }
                        }
                    },
                    {
                        field: 'operate',
                        title: '操作',
                        align: "center",
                        valign: "middle",
                        events: this.operateEvents,
                        formatter: this.operateFormatter //自定义方法，添加操作按钮
                    }
                ]
            });
        },
        queryParams: function (params) {
            return {
                limit: params.limit,   //页面大小
                offset:params.offset
            };
        },
        operateFormatter: function (value, row, index) {
            var result = [];
            result.push('<a href="javascript:void(0);" class="updateFood">修改</a>/');
            result.push('<a href="javascript:void(0);" class="removeFood">删除</a>/');
            return result.join("");
        },
        operateEvents: {
            'click .updateFood': function (e, value, row, index) {
                This.ajaxTable.updateFood(row);
            },
            'click .removeFood': function (e, value, row, index) {
                This.ajaxTable.removeFood(row);
            }
        }
    };

    this.ajaxTable = {
        updateFood: function (row) {
            var form = This.foodtypeForm;
            form.setType("update");
            form.$modal.hintModal().showDiv();
            form.param("picurl").selectImage().setImg(This.path,row["picurl"]);
            form.param("typeid").val(row["typeid"]);
            form.param("typename").val(row["typename"]);
        },
        removeFood:function (row) {
            var errorModal = This.errorBar.hintModal();
            if(row["size"] != 0){
                errorModal.showTheCustom(
                    '<div class="modal-dialog">' +
                    '<div class="modal-content">' +
                    '<div class="modal-body">' +
                    '该分类下存在商品，无法删除' +
                    '</div>' +
                    '<div class="modal-footer">' +
                    '<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>' +
                    '<button type="button" class="btn btn-primary">转移商品</button>' +
                    '</div>' +
                    '</div>' +
                    '</div>'
                );
                This.errorBar.find(".btn-primary").on("click",function () {
                    var form = This.foodtypeTransferForm;
                    This.errorBar.hintModal().hide();
                    form.setType("transfer");
                    form.$modal.hintModal().showDiv();
                    form.param("typeId").val(row["typeid"]);
                });
            }else{
                errorModal.showHint("是否删除",function ($submit) {
                    $submit.attr("disabled",true);
                    $.ajax({
                        url:"foodtype/remove",
                        data:"typeid="+row.typeid,
                        dataType:"json",
                        success:function (data) {
                            if(data["recode"] == "0"){
                                This.tableBar.bootstrapTable("refresh");
                                errorModal.hide();
                            }else{
                                errorModal.showError(data["error"],1200);
                                $submit.attr("disabled",false);
                            }
                        },
                        error:function (value,state,error) {
                            $submit.attr("disabled",false);
                        }
                    });
                });
            }
        }
    };


    var addTool = function (html) {
        This.toolBar.append(html);
    };

    var addMyTool = function (html) {
        $(html).insertBefore(getMyTool("fClear"));
    };

    var getTool = function (name) {
        return This.toolBar.find("."+name);
    };

    var  getMyTool = function (name) {
        return This.myToolBar.find("."+name);
    }
}
